#include "cardMenu.h"
#include "GL/glut.h"
#include "cardStageSelect.h"
#include "cardGame.h"
#include <stdlib.h>
#include "string3d.h"
#include <stdio.h>

//Consntructor
CardStageSelect::CardStageSelect(char gIsSurvival, int gp1, int gp2)
{
	//Parse file with stages
	FILE *file = fopen("mod/stages", "r");

	//Failed to open file
	if (!file)
	{
		printf("Error opening file: mod/stages\n");
		return;
	}

	//Buffer
	char buffer[256];

	//Start parsing
	while (fscanf(file, "%s", buffer) != EOF)
	{
		//Found comment - skip line
		if (buffer[0] == '#')
			fscanf(file, "%*[^\n]"); else
		//Found stage
		if (buffer[0] == '~')
		{
			//Get stage's path
			fscanf(file, "%s", buffer);

			//Create stage's mesh
			Mesh stage;
			stage.load(buffer, 0);

			//Calculate stage's position
			int i = stages.size();
			stage.loc.x = (i & 1) == 0 ? -15.0f : 15.0f;
			stage.loc.z = (i/2) *(15.0f);

			//Stage has obstacles
			if (fscanf(file, "%s", buffer) != EOF && buffer[0] == '{')
			while (1)
			{
				//Get path
				fscanf(file, "%s", buffer);

				//No more obstacles
				if (buffer[0] == '}')
					break;

				//Load obstacle
				Mesh ob;
				ob.load(buffer, 0);

				//Get obstacle's position
				fscanf(file, "%f %f", &ob.loc.x, &ob.loc.z);

				//Add obstacle to stage's mesh
				stage.add(ob);
			}

			//Stage has environment objects
			if (fscanf(file, "%s", buffer) != EOF && buffer[0] == '{')
			while (1)
			{
				//Get path
				fscanf(file, "%s", buffer);

				//No more environment objects
				if (buffer[0] == '}')
					break;

				//Load env object
				Mesh m;
				m.load(buffer, 0);

				//Get objects's position
				fscanf(file, "%f %f", &m.loc.x, &m.loc.z);

				//Add obstacle to stage's mesh
				stage.add(m);
			}

			//Add stage to vector
			stages.push_back(stage);
		}
	}

	//Close file
	fclose(file);

	//Init selection
	prevSel = selection = 0;

	//Animation length
	sAnim.max = 15;

	//Data to pass on
	isSurvival = gIsSurvival;
	p1 = gp1;
	p2 = gp2;
}

void CardStageSelect::input(unsigned char key, bool pressed)
{
	switch (key)
	{
		//Space
		case ' ':
			//Start game
			if (pressed) anim.startFromStart();
			break;

		//Move selection upwards
		case 'w':
			if (pressed	&&  selection >= 2)
			{
				//Save previous selection (for animation)
				prevSel = selection;

				//Move selection
				selection -= 2;

				//Start animation
				sAnim.startFromStart();
			}
			break;
		
		//Move selection downwards
		case 's':
			if (pressed && stages.size() > 2 && selection < stages.size() -2)
			{
				//Save previous selection (for animation)
				prevSel = selection;

				//Move selection
				selection += 2;

				//Start new animation
				sAnim.startFromStart();
			}
			break;

		//Move selection left/right
		case 'a':
		case 'd':
			if (pressed)
			{
				//New selection is shorter that stage array
				if ( (selection ^ 1) < stages.size() )
				{
					//Save previous selection (for animation)
					prevSel = selection;

					//Flips first bit, this flips from odd to even and vice versa
					selection ^= 1;

					//Start new animation
					sAnim.startFromStart();
				}
			}
			break;
	}
}

void CardStageSelect::update()
{
	//Animation changed
	if (anim.update())
		//Animation reached end
		if (anim.isAtEnd())
		{
			//Save data as local, so they can be passed after `delete`
			char isSurv = isSurvival;
			int player1 = p1;
			int player2 = p2;
			int stage = selection;

			//Delete menu
			delete card;
	
			//Start character select screen
			card = new CardGame( isSurv, player1, player2, stage );
		}

	//Update selection animation
	if (sAnim.update())
		//It stopped - update previous selection
		if (sAnim.isAtEnd())
			prevSel = selection;
}

void CardStageSelect::draw()
{
	//Card's animation
	Card::draw();

	//Move camera
	glTranslatef(0.0f, 0.0f, -25.0f);
	glRotatef(45.0f, 1.0f, 0.0f, 0.0f);
	
	/* If selection animation is running, move camera to the interpolated
	 * location of previous and current location, otherwise move camera
	 * to current selection
	 */
	if (sAnim.isRunning())
		glTranslatef(-stages[prevSel].loc.x 
			+sAnim.interpolate(stages[prevSel].loc.x -stages[selection].loc.x), 
			0.0f, 
			-stages[prevSel].loc.z
			+sAnim.interpolate(stages[prevSel].loc.z -stages[selection].loc.z));
	else
		glTranslatef(-stages[selection].loc.x, 0.0f, -stages[selection].loc.z);

	//Draw stages
	for (unsigned int i = 0; i < stages.size(); i++)
		if (selection == i)
		{
			//Seperate X and Y
			float tempX = ((rand() +1) %100) /1000.0f;
			float tempY = ((rand() +1) %100) /1000.0f;

			//Apply offset
			stages[i].loc.x += tempX;
			stages[i].loc.y += tempY;

			//Draw choice
			stages[i].draw();

			//Cancel offset
			stages[i].loc.x -= tempX;
			stages[i].loc.y -= tempY;
		}
		else
			stages[i].draw();
}
